<template>
  <div>
    <div class="allsearch">
      <section class="search-content">
        <el-row :gutter="4" type="flex" justify="start">
          <el-col :span="20">
            <el-input
              v-model="listQuery.name"
              placeholder="请输入名称"
              style="width:150px;"
              @keyup.enter.native="handleFilter"
            />
            <el-cascader
              :change-on-select="true"
              :options="listQuery.courseCategorys"
              v-model="listQuery.courseCategory"
              :props="{value: 'id'}"
              @change="handleFilter"
            />
            <el-select v-model="listQuery.courseStatus" @change="handleFilter">
              <el-option
                v-for="item in listQuery.courseStatusList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <el-button type="primary" @click="handleFilter">搜索</el-button>
            <el-button size="medium" type="info" @click="clearParams">清空</el-button>
            <el-dropdown>
              <el-button type="primary">
                选择课程
                <i class="el-icon-arrow-down el-icon--right"></i>
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <div style="padding:10px;">
                  <el-radio-group v-model="listQuery.courseType" @change="handleFilter">
                    <el-radio label="normal">普通课程</el-radio>
                    <el-radio label="live">直播课程</el-radio>
                    <el-radio label="open">录播公开课</el-radio>
                    <el-radio label="liveOpen">直播公开课</el-radio>
                  </el-radio-group>
                </div>
              </el-dropdown-menu>
            </el-dropdown>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" size="medium" style="float:right;" @click="createSubject">创建课程</el-button>
          </el-col>
        </el-row>
      </section>
    </div>
    <div class="list">
      <el-table
        v-loading="listLoading"
        :data="userList"
        stripe
        border
        fit
        element-loading-text="Loading"
        highlight-current-row
        style="width: 100%;"
      >
        <el-table-column label="课程编号" prop="id" min-width="80" align="center"/>
        <el-table-column
          label="课程名称"
          prop="title"
          min-width="200"
          align="center"
          style="color: blue"
        />
        <el-table-column label="价格" prop="price" min-width="100" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.price }}</span>
          </template>
        </el-table-column>
        <el-table-column label="课程类型" prop="type" min-width="100" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.type | typeFilter }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建者/时间" prop="author" min-width="300" align="center">
          <template slot-scope="scope">
            <el-button type="text" @click="handleClickDialog(scope)">{{ scope.row.userName }}</el-button>
            <br>
            <span>{{ scope.row.createTimeStr }}</span>
          </template>
        </el-table-column>
        <el-table-column class-name="status-col" label="课程状态" width="150" align="center">
          <template slot-scope="scope">
            <el-tag>{{ scope.row.status | statusFilter }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" prop="handle" min-width="150" align="center">
          <template slot-scope="scope">
            <el-dropdown split-button type="primary" @click="handleClick(scope)">
              修改
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-if="scope.row.status === 'published'" @click.native="recommendCourse(scope)">推荐课程</el-dropdown-item>
                <el-dropdown-item
                  v-if="scope.row.status === 'closed' || scope.row.status === 'draft' "
                  @click.native="releaseCourse(scope)"
                >发布课程
                </el-dropdown-item>
                <el-dropdown-item
                  v-if="scope.row.status === 'published'"
                  @click.native="closeCourse(scope)"
                >关闭课程
                </el-dropdown-item>
                <el-dropdown-item @click.native="split(scope)">删除课程</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <coin-dialog
        :visiabledialog="coinDialog"
        :dialog-data="coinData"
        @changeVisiable="coinDialog = false"
      />

      <!-- 推荐序号设置 -->
      <el-dialog :visible.sync="dialogVisible" title="设置推荐课程" width="980px">
        <el-form ref="sequence" :model="sequence" :rules="rules">
          <el-form-item label="序号" prop="num">
            <el-input v-model="sequence.num" style="width: 280px"/>
            请输入长度不能超过8位的整数
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="updateCourse">保 存</el-button>
        </div>
      </el-dialog>

      <pagination
        :total="total"
        :current-page="currentpage"
        :page-size="pagesize"
        @handleSizeChange="handleSizeChange"
        @handleCurrentChange="handleCurrentChange"
      />

      <el-tooltip placement="top" content="返回顶部">
        <back-to-top
          :custom-style="myBackToTopStyle"
          :visibility-height="300"
          :back-position="0"
          transition-name="fade"
        />
      </el-tooltip>
    </div>
  </div>
</template>

<script>
  import {deleteCourse, fetchList, updateCourse} from '@/api/subject/course'
  import {getCategoryList} from '@/api/subject/category'
  import BackToTop from '@/components/BackToTop'
  import Pagination from '@/components/Pagination'
  import CoinDialog from '@/components/Dialog'
  import {scrollTo} from '@/utils/scrollTo'
  import {getUserDetail} from '@/api/operate/userDetail' // 数据接口
  import {getTenantId} from '@/utils/auth'

  export default {
    components: {
      BackToTop,
      Pagination,
      CoinDialog
    },
    filters: {
      statusFilter(status) {
        const statusMap = {
          draft: '未发布',
          published: '已发布',
          closed: '已关闭'
        };
        return statusMap[status]
      },
      typeFilter(type) {
        const typeMap = {
          live: '直播',
          open: '普通公开',
          liveOpen: '公开直播',
          normal: '普通'
        };
        return typeMap[type]
      }
    },
    data() {
      return {
        dialogVisible: false,
        coinDialog: false,
        coinData: {},
        sequence: {
          entity: {},
          num: ''
        },
        listQuery: {
          name: '',
          courseCategory: [],
          courseCategorys: [],
          courseStatus: '',
          courseStatusList: [{value: '', label: '课程状态'}, {value: 'published', label: '已发布'}, {value: 'draft', label: '未发布'}, {value: 'closed', label: '已关闭'}],
          courseType: 'normal'
        },
        currentpage: 1,
        pagesize: 10,
        userList: [],
        listLoading: false,
        published: '',
        draft: '',
        closed: '',
        total: 0,
        myBackToTopStyle: {
          right: '10px',
          bottom: '50px',
          width: '40px',
          height: '40px',
          'border-radius': '4px',
          'line-height': '45px', // 请保持与高度一致以垂直居中 Please keep consistent with height to center vertically
          background: '#e7eaf1'// 按钮的背景颜色 The background color of the button
        },
        rules: {
          num: [
            {required: true, message: '必填信息', trigger: 'blur'},
            {min: 1, max: 8, message: '长度不能超过8位', trigger: 'blur'},
            {pattern: /^[0-9]*[1-9][0-9]*$/, message: '请输入长度不能超过8位的整数'}
          ]
        }
      }
    },
    computed: {},
    created() {
      this.getList();
      this.getCategoryList()
    },
    updated() {
      this.statusfil();
      const data = [this.total, this.published, this.draft, this.closed];
      this.$emit('statistic', data)
    },
    methods: {
      handleClick(scope) {
        // this.$router.push('/subject/cresubject')
        this.$router.push({ name: 'Submanage', params: scope.row })
      },
      handleClickDialog(scope) {
        this.coinDialog = true;
        getUserDetail(scope.row.userId).then(response => {
          this.coinData = response.data.item
        })
      },
      recommendCourse(scope) {
        this.dialogVisible = true;
        this.sequence.entity = scope.row
      },
      updateCourse() {
        this.$refs.sequence.validate((valid) => {
          if (valid) {
            this.dialogVisible = false;
            this.sequence.entity.recommended = 1;
            if (!this.sequence.num) this.sequence.num = 100;
            this.sequence.entity.recommendedSeq = this.sequence.num;
            this.sequence.entity.recommendedTime = new Date();
            updateCourse(this.sequence.entity)
          } else {
            console.log('error submit!!');
            return false
          }
        })
      },
      closeCourse(scope) {
        this.$confirm(`确定关闭这个课程吗`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          scope.row.status = 'closed';
          updateCourse(scope.row).then(() => {
            this.$notify({
              title: '成功',
              message: '课程关闭成功',
              type: 'success',
              duration: 2000
            });
            this.getList()
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消'
          })
        })
      },
      releaseCourse(scope) {
        this.$confirm(`确定发布这个课程吗`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          scope.row.status = 'published';
          updateCourse(scope.row).then(() => {
            this.$notify({
              title: '成功',
              message: '课程发布成功',
              type: 'success',
              duration: 2000
            });
            this.getList()
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消'
          })
        })
      },
      split(scope) {
        this.$confirm(`永久删除这个课程吗`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteCourse(scope.row.id).then(response => {
            if (response.code === 200) {
              this.$notify({
                title: '成功',
                message: '课程已成功删除',
                type: 'success',
                duration: 2000
              });
              this.getList()
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消删除'
          })
        })
      },
      createSubject() {
        this.$router.push('/subject/cresubject')
      },
      handleFilter() {
        this.getList()
      },
      clearParams() {
        this.listQuery.name = '';
        this.listQuery.courseCategory = [];
        this.listQuery.courseStatus = '';
        this.listQuery.courseType = 'normal';
        this.getList()
      },
      getList() {
        this.listLoading = true;
        const params = {};
        params.page = this.currentpage;
        params.pageSize = this.pagesize;
        params.tenantId = getTenantId();
        params.name = this.listQuery.name;
        params.courseCategory = this.listQuery.courseCategory[this.listQuery.courseCategory.length - 1];
        params.courseStatus = this.listQuery.courseStatus;
        params.courseType = this.listQuery.courseType;
        fetchList(params).then(response => {
          response.data.items.map(item => {
            if (item.createTime) item.createTimeStr = new Date(item.createTime).toLocaleString().replace(/[\u4e00-\u9fa5]/g, '').substring(0, 9)
          });
          this.userList = response.data.items;
          this.total = response.data.total;
          this.listLoading = false
        })
      },
      getCategoryList() {
        getCategoryList('course', getTenantId(),'0').then(response => {
          this.listQuery.courseCategorys = response.data.items
        })
      },
      // 挑选已发布 未发布 已关闭的数据 ↓
      statusfil() {
        this.published = this.userList.filter((item) => {
          return item.status === 'published'
        }).length;
        this.draft = this.userList.filter((item) => {
          return item.status === 'draft'
        }).length;
        this.closed = this.userList.filter((item) => {
          return item.status === 'closed'
        }).length
      },
      handleSizeChange(val) {
        this.currentpage = 1;
        this.pagesize = val.value;
        if (this.pagesize >= 20) {
          scrollTo(50, 800)
        }
        this.getList()
      },
      handleCurrentChange(val) {
        this.currentpage = val.value;
        if (this.pagesize >= 20) {
          scrollTo(50, 800)
        }
        this.getList()
      }
    }
  }
</script>

<style lang="scss" scoped>
  .allsearch {
    margin-top: 0;
    margin-bottom: 20px;
    padding: 0;

    .search-content {
      width: 100%;
    }
  }

  .el-table .cell {
    white-space: pre-line;
  }

  .list {
    margin-top: 10px;
  }
</style>
